﻿/*js基础服务*/
(function () {
    Utility = {
        /*option:{first:首次触发，last:最后一次触发}*/
        throttle: function (func, delay, option) {
            var result, timeout;
            var previous = 0;
            var context = this;
            var args = arguments;
            if (!option) {
                option = {};
            }
            var task = function () {
                previous = Date.now();
                result = func.apply(context, args);
                if (timeout) {
                    clearTimeout(timeout);
                    timeout = null;
                }
            }
            //事件执行函数
            return function () {
                var now = Date.now();
                if (!previous && option.first == false) {
                    previous = now;
                }
                var last = now - previous;
                if (last >= delay) {
                    //如果option.first==true会立刻执行
                    task();
                } else if (!timeout && option.last) {
                    //最后一次执行
                    timeout = setTimeout(function () {
                        task();
                    }, delay - last);
                }
                return result;
            }
        },
        debounce: function (func, delay) {
            var result, previous, timeout;
            var context = this;
            var args = arguments;
            var task = function () {
                var now = Date.now();
                var last = now - previous;
                if (last >= delay) {
                    result = func.apply(context, args);
                    if (timeout) {
                        clearTimeout(timeout);
                        timeout = null;
                    }
                } else {
                    if (timeout) {
                        clearTimeout(timeout);
                        timeout = null;
                    }
                    setTimeout(task, delay - last);
                }
            }
            return function () {
                previous = Date.now();
                if (!timeout) {
                    setTimeout(task, delay);
                }
                return result;
            }
        }
    };
    $.extend({
        nullToEmpty: function (data) {
            return data==null?" ":data
            }
    })
})();